import styled from 'styled-components';
import React, {useEffect, useRef, useState} from 'react';
import {useTags} from '../../hooks/useTags';
import {Link} from 'react-router-dom';
import {IconWithName} from '../../components/IconWithName';

const Wrapper = styled.section`
  flex-grow:1;
  font-size: 14px;
  line-height: 22px;
  background: #fff;
  > ol{
    display: flex;
    flex-wrap: wrap;
    margin: 0 16px;
    >li{
      &.selected{
        color: steelblue;
        .icon{
          fill: steelblue;
        }
      }
    }
  }
  >button{
    padding: 0 4px;
    margin-top: 18px;
    margin-bottom: 12px;
    border:none;
    color: #999;
    border-bottom: 1px solid #666;
    background: none;
  }
`;

type Props = {
  value: number;
  onChange: (newValue: number) => void;
}
const TagsSection: React.FC<Props> = (props) => {
  const {tags} = useTags();
  const selectedTagId = props.value;
  const olRef = useRef<HTMLOListElement|null>(null)
  const [iconMargin, setIconMargin] = useState(8)

  useEffect(()=>{
    if(olRef.current === null) return
    const olWidth = olRef.current?.clientWidth
    const calculatedMargin = 8 + (olWidth % 72) / Math.floor(olWidth/72) / 2
    setIconMargin(Math.floor(calculatedMargin))
  }, [olRef])


  const onToggleTag = (tagId: number) => {
    props.onChange(selectedTagId === tagId ? -1 : tagId);
  };
  const isSelected = (tagId: number) => selectedTagId === tagId ? 'selected' : '';

  return (
    <Wrapper className="scroll">
      <ol ref={olRef}>
        {tags.map(tag => (
          <li key={tag.id}
              className={isSelected(tag.id)}
              onClick={() => onToggleTag(tag.id)}>
            <IconWithName tagName={tag.name} category={tag.category} margin={iconMargin}/>
          </li>))}
        <li>
          <Link to="/tags">
            <IconWithName tagName="设置标签" margin={iconMargin} />
          </Link>
        </li>
      </ol>
    </Wrapper>
  );
};


export {TagsSection};